package com.zhiyun.yycall.ui;

import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.RadioButton;
import android.widget.TabHost;

import com.gzit.utils.AndroidUtils;
import com.zhiyun.yycall.R;

/**
 * 页签
 * 
 * @author teddy
 * 
 */
public class MainActivity extends TabActivity {

	private TabHost mHost;
	private Intent callIntent;
	private Intent contactIntent;
	private Intent accountIntent;
	private Intent settingIntent;

	private int[] rids = new int[] { R.id.call_rb, R.id.contact_rb,
			R.id.account_rb, R.id.setting_rb };

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		AndroidUtils.Screen.noWindowTitle(this);
		this.setContentView(R.layout.main_activity);

		// 设置初始的选中状态
		setupTabs();
		initRadioBtn();

		Intent intent = this.getIntent();
		int index = intent.getIntExtra("tabIndex", 0);
		((RadioButton) this.findViewById(rids[index])).setChecked(true);

	}

	private OnCheckedChangeListener switchTabListener = new OnCheckedChangeListener() {

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {

			if (isChecked) {
				int rid = buttonView.getId();

				int[] ids = rids;
				for (int i = 0; i < ids.length; i++) {
					if (rid == ids[i]) {// 找到对应的被按中的radio
						MainActivity.this.mHost.setCurrentTabByTag("tab" + i);
						break;
					}
				}

			}
		}

	};

	private void initRadioBtn() {
		for (int id : rids) {
			((RadioButton) findViewById(id))
					.setOnCheckedChangeListener(switchTabListener);

		}

	}

	private void setupTabs() {

		this.callIntent = new Intent(this, CallActivity.class);
		this.contactIntent = new Intent(this, ContactActivity.class);
		this.accountIntent = new Intent(this, AccountActivity.class);
		this.settingIntent = new Intent(this, SettingActivity.class);
		this.mHost = getTabHost();
		this.mHost.addTab(buildTabSpec("tab0", "tabitem",
				R.drawable.ic_launcher, this.callIntent));

		this.mHost.addTab(buildTabSpec("tab1", "tabitem",
				R.drawable.ic_launcher, this.contactIntent));

		this.mHost.addTab(buildTabSpec("tab2", "tabitem",
				R.drawable.ic_launcher, this.accountIntent));

		this.mHost.addTab(buildTabSpec("tab3", "tabitem",
				R.drawable.ic_launcher, this.settingIntent));

	}

	private TabHost.TabSpec buildTabSpec(String tag, String resLabel,
			int resIcon, final Intent content) {
		return this.mHost.newTabSpec(tag)
				.setIndicator(resLabel, getResources().getDrawable(resIcon))
				.setContent(content);
	}

}
